import numpy as np
import matplotlib.pyplot as plt

'''
k近邻算法训练分类器
'''

class NearestNeighbor:
    def __int__(self):
        pass

    # 训练
    def train(self,X,Y):
        '''
        :param X: N*D的训练集，有N个训练值，每个值是一个矩阵
        :param Y: N个长度的数组
        :return:
        '''
        self.Xtr = X
        self.Ytr = Y

    # 预测
    def predict(self,X):
        '''
        :param X: 预测集
        :return:
        '''
        num_test = X.shape[0]
        Ypred = np.zeros(num_test,dtype=self.Ytr.dtype)

        for i in range(num_test):
            #通过曼哈顿距离去分类这些数据
            distances = np.sum(np.abs(self.Xtr-X[i,:]),axis=1)

            #找到最小距离
            min_index = np.argmin(distances)

            #将预测值复制
            Ypred[i] = self.Ytr[min_index]

        return Ypred

    def show(self,X,x_pred):
        '''
        作图分类
        :param X:
        :param Y:
        :return:
        '''
        plt.figure()
        plt.scatter(X.T[0],X.T[1],color='blue')
        plt.scatter(x_pred.T[0],x_pred.T[1],color='red')
        plt.show()

if __name__ == "__main__":
    x_train = np.array([30, 30, 50, 50, 60, 60, 80, 80, 90, 90, 40, 40, 70, 70]).reshape(7, 2)
    y_train = np.array([1, 1, 0, 0, 0, 1, 0])
    nel = NearestNeighbor()
    nel.train(x_train,y_train)
    x_pred = np.array([40,43,50,46,70,70]).reshape(3,2)
    y_pred = nel.predict(x_pred)
    print(y_pred)

    nel.show(x_train,x_pred)
    # nel.show(x_pred,y_pred,color="red")